package com.xzsoft.gdwz.log.dao.impl;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.xzsoft.gdwz.log.dao.TrdPsEmInfLogDao;
import com.xzsoft.gdwz.model.TrdPsEmInfLog;

/**
 * 日志的数据库操作
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Company: </p> 
 * @author:hellocworld
 * @date:2016年8月30日 下午4:49:15
 */
@Component("trdPsEmInfLogDao")
public class TrdPsEmInfLogDaoImpl implements TrdPsEmInfLogDao {
	
	private static final Logger logger = LoggerFactory .getLogger(TrdPsEmInfLogDaoImpl.class); 
	
	private final String entityName = "trd_ps_em_inf_log";
	@Autowired
	private MongoTemplate mongoTemplate;
	
	public int insertTrdPsEmInfLog(TrdPsEmInfLog trdPsEmInfLog) {
		try {
			//初始化插入时间
			DateTime dateTime = new DateTime();
			trdPsEmInfLog.setCreateDate(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
			mongoTemplate.insert(trdPsEmInfLog, entityName);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}
	/**
	 * 查询
	 */
	public String findByCondition(TrdPsEmInfLog log) {
		Query query = new Query();
		if(log.getEmName() != null&&!"".equals(log.getEmName())){
			query.addCriteria(Criteria.where("emName").regex(log.getEmName()));
		}
		
		if(log.getOrderId() != null&&!"".equals(log.getOrderId())){
			query.addCriteria(Criteria.where("orderId").regex(log.getOrderId()));
		}
		
		if(log.getCreateDate() != null && !"".equals(log.getCreateDate())){
			query.addCriteria(Criteria.where("createDate").gte(log.getCreateDate()));
		}
		query.with(new Sort(Direction.DESC, "createDate"));
		query.skip((log.getPage()-1)*log.getRows());
		query.limit(log.getRows());
		List<TrdPsEmInfLog> list = mongoTemplate.find(query, TrdPsEmInfLog.class, entityName);
		Long count = mongoTemplate.count(query, TrdPsEmInfLog.class, entityName);
		JSONObject obj = new JSONObject();
		obj.put("total", count);
		obj.put("rows",list);
		return obj.toString();
	}
	/**
	 * 删除
	 */
	public void delLog(String ids) {
		Criteria criatira = new Criteria();
		List idList = Arrays.asList(ids.split(","));
		criatira.andOperator(Criteria.where("id").in(idList));
		Query query = new Query(criatira);
		mongoTemplate.remove(query, TrdPsEmInfLog.class, entityName);
	}
}
